<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
</head>
<body>
    姓名：<input type="text" value="" id="userName">
    发送消息：<input type="text" value="" id="message">
    <button type="button" onclick="onOpen()">连接</button>
    <button type="button" onclick="sendMessage()">发送消息</button>

    <div style="border: 1px solid red;" id="content"></div>
</body>
<script src="js/jquery-3.4.1.min.js"></script>
<script>

    //链接websocket
    var target = "ws:localhost:8080/chat";
    var ws;//一个ws对象就是一个通信管道

    //连接
    function onOpen(){
        let userName = $("#userName").val();
        ws = new WebSocket(target+"?userName="+userName);
        ws.onopen = function(){
            let msgSpan = "<span>连接成功!</span>";
            $("#content").append(msgSpan);
        }

        ws.onmessage = function(data){
            let msgSpan = "<span>"+data.data+"</span>";
            $("#content").append(msgSpan);
        }
    }

    function sendMessage() {
        let message = $("#message").val();
        let msgSpan = "<span>client:"+message+"</span>";
        $("#content").append(msgSpan);
        ws.send(message);
    }




</script>
</html>